/*********************************************************************************
 *      Copyright:  (C) 2022 guoyi<675088383@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  ds18b20.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(11/12/21)
 *         Author:  guoyi<675088383@qq.com>
 *      ChangeLog:  1, Release initial version on "21/12/21 10:24:19"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>

#include "ds18b20.h"
#include "zlog_api.h"


int get_temperature(float *temper)
{
    char            w1_path[64] = "/sys/bus/w1/devices/";
    char            chip[32];
    char            buf[128];
    DIR            *dirp;
    struct dirent  *direntp;
    int             fd = -1;
    char           *ptr;
    int             found = 0;

    if( !temper )
    {
        return -1;
    }

    if((dirp = opendir(w1_path)) == NULL)
    {
        log_warn("Opendir '%s' error: %s\n", w1_path, strerror(errno));
        return -2;
    }

    while((direntp = readdir(dirp)) != NULL)
    {
        if(strstr(direntp->d_name,"28-"))
        {
            strncpy(chip, direntp->d_name, sizeof(chip));
            found = 1;
            break;
        }
    }
    closedir(dirp);

    if( !found )
    {
        log_warn("Can not find ds18b20 in '%s'\n", w1_path);
        return -3;
    }

    strncat(w1_path, chip, sizeof(w1_path)-strlen(w1_path));
    strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));

    if( (fd=open(w1_path, O_RDONLY)) < 0 ) 
    { 
        log_warn("open %s error: %s\n", w1_path, strerror(errno)); 
        return -4;
    } 

    if(read(fd, buf, sizeof(buf)) < 0)
    {
        log_warn("read %s error: %s\n", w1_path, strerror(errno)); 
        return -5;
    } 

    ptr = strstr(buf, "t=");
    if( !ptr )
    {
        log_warn("ERROR: Can not get temperature\n");
        return -6;
    }

    *temper = atof(ptr+=2)/1000;

    close(fd);
    return 0;
}
